package sellControllers

import (
	"WEB/models"
	"WEB/models/sellModel"
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"log"
)

type SellUserController struct {
	SellBaseController
}

// @router /sell/login [get]
func (this *SellUserController) GetLogin() {
	this.TplName = "sell/login.html"
}

// @router /sell/login [post]
func (this *SellUserController) PostLogin() {
	user := sellModel.SellUser{}
	if err := this.ParseForm(&user); err != nil {
		panic(err)
	} else {
		//check if is exsit
		orm := orm.NewOrm()
		sql := models.QueryByEqualField(user, "UserName", "UserPassword")
		var temp sellModel.SellUser
		err := orm.Raw(sql, user.UserName, user.UserPassword).QueryRow(&temp)
		if err != nil {
			this.TplName = "error.html"
			this.Data["msg"] = "账号密码错误"
			return
		}

		var store models.Stores
		sql = models.QueryByPrimaryKey(store)
		err = orm.Raw(sql, temp.UserStoreId).QueryRow(&store)
		//寻找用户的商铺
		if err == nil && store.StoresId != 0 {
			this.SetSession("store", store)
		}
		this.SetSession("sell_Username", user.UserName)
		this.SetSession("sell_isLogin", "true")
		this.SetSession("sell_User", temp)
		this.Redirect("/sell/index", 302)
	}
}

// @router /sell/logout [get]
func (this *SellUserController) GetLogout() {
	isLogin := this.GetSession("sell_isLogin")
	if isLogin == "true" {
		this.SetSession("sell_Username", nil)
		this.SetSession("sell_isLogin", "fasle")
		this.SetSession("sell_User", nil)
		this.SetSession("store", nil)

	}
	this.Redirect("/sell/index", 302)
}

//@router /sell/register [get]
func (this *SellUserController) GetRegister() {
	this.TplName = "sell/register.html"
}

//@router /sell/register [post]
func (this *SellUserController) PostRegister() {
	u := sellModel.SellUser{}
	if err := this.ParseForm(&u); err != nil {
		this.TplName = "error.html"
	}
	fmt.Println(u)
	//验证表单信息
	valid := validation.Validation{}

	valid.Required(u.UserName, "UserName")
	valid.Required(u.UserPassword, "UserPassword")
	valid.Required(u.UserEmail, "Email")
	valid.Required(u.UserPhone, "UserPhone")

	valid.MaxSize(u.UserName, 63, "nameMax")
	valid.Phone(u.UserPhone, "UserPhone")
	valid.Email(u.UserEmail, "email")

	if valid.HasErrors() {
		msg := make([]string, 0)
		for _, v := range valid.Errors {
			msg = append(msg, v.Error())
		}
		this.Data["msg"] = msg
		log.Println("错误", msg)
		this.TplName = "error.html"
		return
	}
	newOrm := orm.NewOrm()
	sql := models.QueryByEqualField(u, "UserName")
	var temp sellModel.SellUser
	fmt.Println("sql", sql)
	row := newOrm.Raw(sql, u.UserName).QueryRow(&temp)
	if row == nil {
		this.Data["msg"] = "账号已经被使用"
		this.TplName = "error.html"
		return
	}
	sql = models.InsertWithoutPrimaryKey(sellModel.SellUser{})
	fmt.Println("sql", sql)
	value := models.GetFieldValue(u, models.IsPrimaryKey)
	fmt.Println(value)
	_, row = newOrm.Raw(sql, value).Exec()
	if row != nil {
		panic(row)
	}
	this.Redirect("/sell/login", 302)
}

// @router /sell/index [get]
func (this *SellUserController) GetIndexPage() {
	session := this.GetSession("store")
	if session != nil {
		store := session.(models.Stores)
		goods := GetAllSellGoodByStore(store.StoresId, true)
		kinds, err := models.GetAllParentGoodKindByStoreId(store.StoresId)
		if err != nil {
			fmt.Println(err)
			this.Redirect("/error", 302)
			return
		}
		this.Data["GoodsKind"] = kinds
		this.Data["Goods"] = goods
	}
	this.TplName = "sell/index.html"
}

// @router /sell/ [get]
func (this *SellUserController) GetRoot() {
	this.GetIndexPage()
}

// @router /sell/kindManage [get]
func (this *SellUserController) GetKindManage() {
	store := this.GetSession("store").(models.Stores)
	kinds, err := models.GetAllParentGoodKindByStoreId(store.StoresId)
	if err != nil {
		panic(err)
	}
	this.Data["GoodKinds"] = kinds
	this.Data["SystemType"] = models.GetSystemType()
	this.TplName = "sell/kindManage.html"
}

// @router /sell/getKinds [get]
func (this *SellUserController) GetKinds() {
	store := this.GetSession("store").(models.Stores)
	kinds := models.GetAllGoodKindByStoreId(store.StoresId)
	this.Data["json"] = map[string]interface{}{
		"code": 0,
		"data": kinds,
	}
	this.ServeJSON()
}

// @router /sell/addFaterKind [post]
func (this *SellUserController) AddParentKinds() {
	name := this.GetString("parentName")
	if name == "" {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
		}
		this.ServeJSON()

	} else {
		var kind models.GoodsKind
		store := this.GetSession("store").(models.Stores)
		kind.GoodsStoreId = store.StoresId
		kind.GoodsKindName = name
		sql := `
			INSERT INTO goods_kind
			(goods_store_id,goods_kind_name)
			VALUES
			(?,?)
		`
		newOrm := orm.NewOrm()
		_, e := newOrm.Raw(sql, store.StoresId, name).Exec()
		if e != nil {
			panic(e)
			this.Data["json"] = map[string]interface{}{
				"code": 1,
			}
		} else {
			this.Data["json"] = map[string]interface{}{
				"code": 0,
			}
		}
		this.ServeJSON()
	}
}

// @router /sell/addSecondKind [post]
func (this *SellUserController) AddSecondKinds() {
	name := this.GetString("secondName")
	systemId, err := this.GetInt("systemId")

	if err != nil {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
		}
		this.ServeJSON()
		return
	}
	parentId, err := this.GetInt("parentId")
	if err != nil {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
		}
		this.ServeJSON()
		return
	}

	if name == "" {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
		}
		this.ServeJSON()

	} else {

		var kind models.GoodsKind
		store := this.GetSession("store").(models.Stores)
		kind.GoodsStoreId = store.StoresId
		kind.GoodsKindParent = parentId
		kind.SystemKindId = systemId
		kind.GoodsKindName = name
		sql := models.InsertWithoutPrimaryKey(kind)
		newOrm := orm.NewOrm()
		_, e := newOrm.Raw(sql, models.GetFieldValue(kind, models.IsPrimaryKey)).Exec()
		if e != nil {
			panic(e)
			this.Data["json"] = map[string]interface{}{
				"code": 1,
			}
		} else {
			this.Data["json"] = map[string]interface{}{
				"code": 0,
			}
		}
		this.ServeJSON()
	}
}

// @router /sell/deleteKind [post]
func (this *SellUserController) DelKinds() {
	kindId, err := this.GetInt("kindId")
	if err != nil {
		panic(err)
	}
	var kind models.GoodsKind
	sql := models.DeleteByPrimaryKey(kind)
	_, err = orm.NewOrm().Raw(sql, kindId).Exec()
	if err != nil {
		panic(err)
	}
	this.Data["json"] = map[string]interface{}{
		"code": 0,
		"msg":  "ok",
	}
	this.ServeJSON()
}
